package edu.qd.learn.day06;

import java.io.InputStream;

/**
 * 链式存储结构
 *
 * @author 布衣
 */
public class LearnLinkForList {

    //头指针
    private Node head;
    private Node tail;

    //节点
    //成员内部类
    private class Node {
        int val;
        Node next;
        public Node(int val) {
            this.val = val;
        }
        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 向链表时硕添加一个新元素 | 尾
     *
     * @return
     */
    public boolean add(int val) {
        if (head != null) {
            tail.next = new Node(val);
            tail = tail.next;
            return true;
        }

        head = new Node(val);
        tail = head;
        return true;
    }
    //来一段多线程 实现通信

    /**
     * 返回头节点
     * @return
     */
    public Node getHead(){
        return head;
    }

    /**
     * 按值 删除，找到第一个满足条件的节点，然后删除它
     * @param val  值
     * @return
     */
    public boolean deleteByValue(int val){
        Node temp = head;
        //删除头节点
        if(head!= null && head.val == val){
            head = head.next;
            temp.next = null;
            return true;
        }

        Node preNode = head;

        while(temp != null && temp.val != val){
            preNode = temp;
            temp = temp.next;
        }
        if(temp == tail){
            tail = preNode;
        }
        preNode.next = temp.next;
        temp = null;
        return true;
    }

    public static void main(String[] args) {
        LearnLinkForList llfl = new LearnLinkForList();
        llfl.add(1);
        llfl.add(2);
        llfl.add(3);
        llfl.add(4);
        llfl.add(5);
        llfl.add(6);

        llfl.deleteByValue(6);
        llfl.add(7);

        Node temp = llfl.getHead();
        while(temp != null){
            System.out.println(temp.val);
            temp = temp.next;
        }
    }


    // N个节点 按照某结构 组成


}
